const express = require("express");
const router = express.Router();
const userDB = require("../../database/userinfo"); //用户表操作
const messageDB = require("../../database/message"); //留言表操作
const linkDB = require("../../database/link"); //留言表操作
const articleDB = require("../../database/article");
// 请求获取留言数据
router.get("/msg", async (req, res) => {
  // 查询留言的所有数据  连表查询
  let msgDoc = await messageDB.find({},{},{sort:{date:-1}}).populate("author", {
    password: 0,
    __v: 0,
    admin: 0
  }).populate("children.author", {
    password: 0,
    __v: 0,
    admin: 0
  }).populate("children.replyUser", {
    password: 0,
    __v: 0,
    admin: 0
  }) //  同时查询写子级回复的用户id
  // console.log(msgDoc);
  res.send({
    code: 0,
    message: "留言请求成功",
    data: msgDoc,
  })
});

// 获取友链数据
router.get("/link", async (req,res)=>{
  let linkDoc =  await linkDB.find();
  res.send({
    code:0,
    message:"成功获取友链数据",
    data:linkDoc,
  });

})

// 获取全部文章数据
router.get("/article",async (req,res)=>{
  let articleDoc = await articleDB.find();
  // 根据阅读数排序
  // let articleDoc = await articleDB.find({},{},{sort:{readingNum:-1}})
  if(articleDoc.length === 0){
    res.send({
      code:1,
      message:"暂无文章"
    })
  }else{
    res.send({
      code:0,
      message:"成功获取所有文章数据",
      data:articleDoc,
    })
  }
});

// 获取文章详情页的数据
router.get("/articleDetails", async (req,res)=>{
  let {id} = req.query;
  let doc =  await articleDB.findById(id);
  if(!doc) return res.send({code:1, message:"文章id有误，查不到这篇文章"});
  await articleDB.findByIdAndUpdate(id,{$inc:{readingNum:1}}); //设置字段值自增1
  // 查到数据时
  res.send({
    code:0,
    message:"查询成功",
    data:doc,
  })
})

// 监听反馈,留言联系
router.get("/contact", async (req,res)=>{
  
})
// 导出
module.exports = router;